 /*
 * @name: 运费模版/新增/编辑
 * @Author: along
 * @Date: 2020-06-18
 * @Last Modified by: mikey.zhaopeng
 * @Last Modified time: 2021-04-12 09:12:03
 */
<template>
    <div class="marketgoodfreightEdit goodfreightEdit">
        <!-- header -->
        <div class="header-nav">
            {{ template_no ? '编辑运费模版' : '新增运费模版' }}
        </div>

        <!-- form -->
        <div class="form">
            <el-form
                :model="ruleForm"
                :rules="rules"
                ref="ruleForm"
                label-width="120px"
                :label-position="'right'"
            >
                <el-form-item
                    label="排序"
                    prop="template_sort"
                >
                    <el-input
                        v-model="ruleForm.template_sort"
                        size="small"
                        placeholder="序号越小,排列越往前"
                        type="number"
                        :min="0"
                        style="width:488px"
                        v-inserted
                    />
                </el-form-item>
                <el-form-item
                    label="运费模版名称"
                    prop="template_name"
                >
                    <el-input
                        v-model="ruleForm.template_name"
                        size="small"
                        placeholder="请填写模版名称"
                        style="width:488px"
                    />
                </el-form-item>
                <el-form-item
                    label="计费方式"
                    prop="freight_type"
                >
                    <el-radio-group v-model="ruleForm.freight_type">
                        <el-radio :label="0">
                            按重量计费
                        </el-radio>
                        <el-radio :label="1">
                            按件计费
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item
                    label="配送方式"
                    prop="freight_json"
                >
                    <div class="wrap">
                        <div class="wrap-table">
                            <el-table
                                :data="ruleForm.freight_json"
                                height="100%"
                                style="width: 100%;"
                                border
                                ref="freightTable"
                            >
                                <el-table-column
                                    prop="area_list"
                                    label="运送到"
                                    show-overflow-tooltip
                                    :formatter="emptyFormatter"
                                    align="left"
                                    :max-height="180"
                                >
                                    <template slot-scope="scope">
                                        <div class="zd-city-name">
                                            <div class="zd-city-list">
                                                <p
                                                    v-for="(item,index) in scope.row.area_list"
                                                    :key="index"
                                                >
                                                    {{ item.name }} {{ (index == 0 && scope.row.area_list.length == 1) || (index == scope.row.area_list.length - 1) ? '' : ';' }}
                                                </p>
                                            </div>
                                            <p
                                                class="zd-city-name-edit"
                                                @click="fnEditCity(scope.$index)"
                                                v-if="scope.$index > 0"
                                            >
                                                编辑
                                            </p>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="freight_num_start"
                                    :label="!ruleForm.freight_type ? '首重(kg)' : '首件(件)' "
                                    :formatter="emptyFormatter"
                                    align="left"
                                >
                                    <template slot-scope="scope">
                                        <el-input
                                            v-model="scope.row.freight_num_start"
                                            clearable
                                            size="small"
                                            style="width:100px;height:36px"
                                            type="number"
                                            @input="scope.row.freight_num_start = /^\d+\.?\d{0,1}$/.test(scope.row.freight_num_start)|| scope.row.freight_num_start == '' ? scope.row.freight_num_start : (scope.row.freight_num_start = scope.row.freight_num_start.split('.')[0] + '.' + scope.row.freight_num_start.split('.')[1].slice(0,1)) "
                                        />
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="freight_fee_start"
                                    :label="!ruleForm.freight_type ? '首重价格(元)' : '首件运费(元)' "
                                    :formatter="emptyFormatter"
                                    align="left"
                                >
                                    <template slot-scope="scope">
                                        <el-input
                                            v-model="scope.row.freight_fee_start"
                                            clearable
                                            size="small"
                                            style="width:100px;height:36px"
                                            type="number"
                                            @input="scope.row.freight_fee_start = /^\d+\.?\d{0,2}$/.test(scope.row.freight_fee_start)|| scope.row.freight_fee_start == '' ? scope.row.freight_fee_start : (scope.row.freight_fee_start = scope.row.freight_fee_start.split('.')[0] + '.' + scope.row.freight_fee_start.split('.')[1].slice(0,2)) "
                                        />
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="freight_num_other"
                                    :label="!ruleForm.freight_type ? '续重(kg)' : '续件(件)' "
                                    :formatter="emptyFormatter"
                                    align="left"
                                >
                                    <template slot-scope="scope">
                                        <el-input
                                            v-model="scope.row.freight_num_other"
                                            clearable
                                            size="small"
                                            style="width:100px;height:36px"
                                            type="number"
                                            @input="scope.row.freight_num_other = /^\d+\.?\d{0,1}$/.test(scope.row.freight_num_other)|| scope.row.freight_num_other == '' ? scope.row.freight_num_other : (scope.row.freight_num_other = scope.row.freight_num_other.split('.')[0] + '.' + scope.row.freight_num_other.split('.')[1].slice(0,1)) "
                                        />
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="freight_fee_other"
                                    label="续费(元)"
                                    :formatter="emptyFormatter"
                                    align="left"
                                >
                                    <template slot-scope="scope">
                                        <el-input
                                            v-model="scope.row.freight_fee_other"
                                            clearable
                                            size="small"
                                            style="width:100px;height:36px"
                                            type="number"
                                            @input="scope.row.freight_fee_other = /^\d+\.?\d{0,2}$/.test(scope.row.freight_fee_other)|| scope.row.freight_fee_other == '' ? scope.row.freight_fee_other : (scope.row.freight_fee_other = scope.row.freight_fee_other.split('.')[0] + '.' + scope.row.freight_fee_other.split('.')[1].slice(0,2)) "
                                        />
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="freight_fee_none"
                                    label="邮费满额包邮(元)"
                                    :formatter="emptyFormatter"
                                    align="left"
                                    :width="150"
                                >
                                    <template slot-scope="scope">
                                        <el-input
                                            v-model="scope.row.freight_fee_none"
                                            clearable
                                            placeholder="选填"
                                            size="small"
                                            style="width:100px;height:36px"
                                            type="number"
                                            @input="scope.row.freight_fee_none = /^\d+\.?\d{0,2}$/.test(scope.row.freight_fee_none)|| scope.row.freight_fee_none == '' ? scope.row.freight_fee_none : (scope.row.freight_fee_none = scope.row.freight_fee_none.split('.')[0] + '.' + scope.row.freight_fee_none.split('.')[1].slice(0,2)) "
                                        />
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    label="操作"
                                    align="left"
                                >
                                    <template slot-scope="scope">
                                        <el-button
                                            type="text"
                                            v-if="scope.$index > 0"
                                            @click="fnRemoveCity(scope.$index)"
                                        >
                                            删除
                                        </el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                        <div
                            class="wrap-add"
                            @click="fnChangeregion('add_city')"
                        >
                            <i class="el-icon-plus" />
                            指定区域设置运费
                        </div>
                        <div class="wrap-desc">
                            {{ !ruleForm.freight_type ? '根据重量来计算运费，当物品不足《首重重量》时，按照《首重费用》计算，超过部分按照《续重重量》和《续重费用》乘积来计算' : '根据件数来计算运费，当物品不足《首件数量》时，按照《首件费用》计算，超过部分按照《续件重量》和《续件费用》乘积来计算' }}
                        </div>
                        <div class="wrap-text">
                            除指定区域外，其余地区的运费采用“全国【默认运费】”进行计算
                        </div>
                    </div>
                </el-form-item>
                <div class="form-region">
                    特殊区域设置
                </div>
                <el-form-item
                    label="类型"
                >
                    <el-radio-group
                        v-model="ruleForm.delivery_type"
                        @change="ruleForm.delivery_json = []"
                    >
                        <el-radio :label="-1">
                            不配送区域
                        </el-radio>
                        <el-radio :label="1">
                            只配送区域
                        </el-radio>
                    </el-radio-group>
                    <br>
                    <p class="form-region-text">
                        不配送区域：不配送此处选择的区域，只配送此处选择区域之外的地方<br>
                        只配送区域：只配送此处选择的区域，不配送此处选择区域之外的地方<br>
                        只能选择一种类型
                    </p>
                </el-form-item>
                <el-form-item
                    :label="ruleForm.delivery_type == 1 ? '只配送区域' : '不配送区域' "
                >
                    <div
                        class="form-change-region"
                        @click="fnChangeCity()"
                    >
                        <p v-if="ruleForm.delivery_json.length == 0">
                            选择区域
                        </p>
                        <div
                            v-else
                            class="form-region-city"
                        >
                            <p
                                v-for="(item,index) in ruleForm.delivery_json"
                                :key="index"
                            >
                                {{ item.name }} {{ (index == 0 && ruleForm.delivery_json.length == 0) || (index == ruleForm.delivery_json.length - 1) ? '' : ';' }}
                            </p>
                        </div>
                    </div>
                </el-form-item>
                <el-form-item
                    label="状态"
                >
                    <el-radio-group v-model="ruleForm.template_status">
                        <el-radio :label="1">
                            启用
                        </el-radio>
                        <el-radio :label="0">
                            禁用
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
        </div>
        <div class="zd-foot">
            <el-button
                size="small"
                type="default"
                style="width:120px;height:36px"
                @click="()=>{
                    this.$router.push({
                        name: 'goodsFreight'
                    })
                }"
            >
                返回运费列表
            </el-button>
            <el-button
                size="small"
                type="primary"
                style="width:120px;height:36px;margin-left:36px"
                @click="fnSubmit('ruleForm')"
            >
                提交
            </el-button>
        </div>

        <!-- 选择区域弹窗 -->
        <region-dialog
            ref="region"
            @setData="getData"
            @editData="editData"
        />
    </div>
</template>

<script>
import regionDialog from '@/components/manage/market/region-dialog';
export default {
    mixins: [],
    components: {
        regionDialog
    },
    data () {
        const validateJson = (rule, value, callback) => {
            if (value) {
                let flag = false;

                for(let key=0; key<value.length; key++){
                    if(value[key].freight_num_start == '' || value[key].freight_fee_other == '' || value[key].freight_fee_start == '' || value[key].freight_num_other == '') {
                        flag = true;
                    }
                }

                if(flag) {
                    callback('必填项不可以为空');
                } else {
                    callback();
                }
            } else {
                callback();
            }
        };

        return {
            template_no: '',//模版编号
            ruleForm: {
                template_sort: '',//排序
                template_name: '',//模版名称
                freight_type: 0,//计费方式
                delivery_type: -1,//配送类型
                template_status: 0,//模版状态
                freight_json: [{
                    area_list: [{
                        id: 0,
                        name: '全国'
                    }],
                    freight_num_start: '',
                    freight_fee_start: '',
                    freight_num_other: '',
                    freight_fee_other: '',
                    freight_fee_none: ''
                }],//邮费设置
                delivery_json: [],//配送区域
            },
            rules: {
                template_sort: [
                    { required: true, message: '请填写排序号', trigger: 'change' }
                ],
                template_name: [
                    { required: true, message: '请填写排序号', trigger: 'change' }
                ],
                freight_json: [
                    { validator: validateJson, trigger: ['blur','change'] }
                ]
            }
        };
    },
    filters: {},
    computed: {},
    directives: {
        inserted (el, binding, vnode, oldVnode) {
            el.addEventListener("keypress",e => {
                /* eslint-disable */
                e = e || window.event;
                let charcode = typeof e.charCode === 'number' ? e.charCode : e.keyCode;
                let re = /\d/;
                if(!re.test(String.fromCharCode(charcode)) && charcode > 9 && !e.ctrlKey){
                    if(e.preventDefault){
                        e.preventDefault();
                    }else{
                        e.returnValue = false;
                    }
                }
            });
        }
    },
    watch: {},
    created () {
        if(process.client){
            let query = this.$route.query;

            if(query.template_no) {
                this.template_no = query.template_no;
                this.getInfo();
            }
            this.$store.commit('theme/SET_BREAD', [
                {title: '店铺设置'},
                {title: '增运费模板', path: '/manage/market/good-freight', query: {}},
                {title: query.template_no ? '编辑运费模板': '新增运费模板'}
            ]);
        }
    },
    mounted () {
    },
    methods: {
        /**
         * 获取模版数据
         */
        getInfo () {
            this.$post('/Freight/info',{
                template_no: this.template_no
            }, resp=>{
                if(resp.code == 1) {
                    this.ruleForm = {
                        delivery_json: resp.data.delivery_list,
                        template_sort: resp.data.template_sort,
                        template_name: resp.data.template_name,
                        freight_type: resp.data.freight_type == 'weight' ? 0 : 1,
                        delivery_type: Number(resp.data.delivery_type),
                        template_status: resp.data.template_status,
                        freight_json: resp.data.freight_list
                    };
                } else {
                    this.$notify({
                        title: '提示',
                        message: resp.msg,
                        type: 'warning'
                    });
                }
            });
        },

        /**
         * 提交数据
         */
        fnSubmit (formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {

                    let data = {
                        template_name: this.ruleForm.template_name,
                        freight_type: this.ruleForm.freight_type == 0 ? 'weight' : 'num',
                        freight_json: JSON.stringify(this.ruleForm.freight_json),
                        delivery_type: this.ruleForm.delivery_type,
                        delivery_json: JSON.stringify(this.ruleForm.delivery_json),
                        template_sort: this.ruleForm.template_sort,
                        template_status: this.ruleForm.template_status
                    };

                    if(!this.template_no) { //新增
                        this.$post('/Freight/save', data, resp=>{
                            if(resp.code == 1) {
                                this.$notify({
                                    title: '成功',
                                    message: '提交成功',
                                    type: 'success'
                                });

                                setTimeout(()=>{
                                    this.$router.push({
                                        name: 'goodsFreight'
                                    });
                                },500);
                            } else {
                                this.$notify({
                                    title: '提示',
                                    message: resp.msg,
                                    type: 'warning'
                                });
                            }
                        });
                    } else { //编辑
                        data.template_no = this.template_no;
                        this.$post('/Freight/save', data, resp=>{
                            if(resp.code == 1) {
                                this.$notify({
                                    title: '成功',
                                    message: '编辑成功',
                                    type: 'success'
                                });

                                setTimeout(()=>{
                                    this.$router.push({
                                        name: 'goodsFreight'
                                    });
                                },500);
                            } else {
                                this.$notify({
                                    title: '提示',
                                    message: resp.msg,
                                    type: 'warning'
                                });
                            }
                        });
                    }
                } else {
                    // console.log('error submit!!');
                    return false;
                }
            });
        },

        /**
         * 删除运费模版
         */
        fnRemoveCity (index) {
            this.ruleForm.freight_json.splice(index,1);
        },

        /**
         * 编辑模版数据
         */
        fnEditCity (index) {
            let freightList = this.ruleForm.freight_json;
            let checkList = freightList[index].area_list;
            let list = [];

            for(let i=0; i<freightList.length; i++) {
                if(i > 0) {
                    list = list.concat(freightList[i].area_list);
                }
            }

            this.$refs.region.getDialogType('edit', true);
            this.$refs.region.getEditList(list, checkList,index);
            this.$refs.region.show();
        },

        /**
         * 打开弹窗
         *      1.新增指定区域设置运费
         *      2.选择配送/不配送区域
         * @param   {String}    type    //add_city：新增运费模版
         */
        fnChangeregion (type) {
            if(this.ruleForm.freight_json.length == 1) {
                this.$refs.region.getDialogType(type);
                this.$refs.region.show();
            } else {
                let list = JSON.parse(JSON.stringify(this.ruleForm.freight_json));
                let arr = [];

                for(let key=0; key<list.length; key++) {
                    if(key > 0) {
                        arr = arr.concat(list[key].area_list);
                    }
                }
                this.$refs.region.getDialogType(type);
                this.$refs.region.setData(arr);
                this.$refs.region.show();
            }
        },

        /**
         * 选择指定区域
         */
        fnChangeCity () {
            this.$refs.region.getDialogType('edit', false);
            this.$refs.region.getEditList(this.ruleForm.delivery_json, this.ruleForm.delivery_json, '');
            this.$refs.region.show();
        },

        /**
         * 获取编辑时数据
         * @param   {Boolean}   param   //true: 选择区域编辑    false:配送方式编辑
         */
        editData (resp) {
            if(resp.param) {
                this.ruleForm.freight_json[resp.index].area_list = JSON.parse(resp.data);
            } else {
                this.ruleForm.delivery_json = JSON.parse(resp.data);
            }
        },

        /**
         * 获取新增时选择的数据
         */
        getData (resp) {
            if(resp.type == 'add_city') {
                let freight_list = [{
                    area_list: JSON.parse(resp.data),
                    freight_num_start: '',
                    freight_fee_start: '',
                    freight_num_other: '',
                    freight_fee_other: '',
                    freight_fee_none: ''
                }];

                this.ruleForm.freight_json = this.ruleForm.freight_json.concat(freight_list);
            } else if (resp.type == 'add_region') {
                this.ruleForm.delivery_json = JSON.parse(resp.data);
            }
            // console.log(JSON.parse(resp.data), resp.type, 'resp');
        },

        /**
         * 过滤函数
         */
        emptyFormatter(row, column, val) {
            if (!val) return '--';
            return val;
        }
    }
};
</script>

<style lang="less" scoped>
.marketgoodfreightEdit {
    background-color: #fff;
    display: flex;
    flex-direction: column;
    position: relative;
    width: 100%;
    min-height: calc(100vh - 80px);
    box-sizing: border-box;
    padding-bottom: 50px;
    .header-nav {
        width: 100%;
        height: 42px;
        display: flex;
        align-items: center;
        padding-left: 32px;
        color: #3F454B;
        font-size: 16px;
        font-weight: 500;
        border-bottom: 1px #F0F2F7 solid;
    }
    .form {
        margin: 24px 32px 0 32px;
        background:rgba(250,250,250,1);
        border:1px solid rgba(238,238,238,1);
        box-sizing: border-box;
        padding: 24px 32px 28px 14px;
    }
    .wrap {
        width: 100%;
        background:rgba(251,251,251,1);
        border:1px solid rgba(238,238,238,1);
        box-sizing: border-box;
        padding: 24px;
        .wrap-add {
            height: 36px;
            width: 100%;
            border-radius:4px;
            border:1px dashed rgba(184,184,184,1);
            display: flex;
            justify-content: center;
            align-items: center;
            color: #20A0FF;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            .el-icon-plus {
                font-weight: bold;
                margin-right: 10px;
            }
        }
        .wrap-desc {
            color: #666666;
            font-size: 14px;
            height: 14px;
            line-height: 14px;
            margin: 16px 0 0 0;
        }
        .wrap-text {
            color: #333333;
            font-size: 14px;
        }
        .wrap-table {
            width: 100%;
            box-sizing: border-box;
            // border: 1px red solid;
            margin-bottom: 20px;
            .zd-city-name {
                display: flex;
                align-items: center;
                white-space: nowrap;
                .zd-city-list {
                    display: block;
                    align-items: center;
                    white-space: nowrap;
                    width: 120px;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    p {
                        display: inline-block;
                    }
                }
                &-edit {
                    color: #20A0FF;
                    font-size: 14px;
                    text-decoration: underline;
                    cursor: pointer;
                    margin-left: 5px;
                }
            }
        }
    }
    .form-region {
        width: 100%;
        box-sizing: border-box;
        border-bottom: 1px #f2f2f2 solid;
        height: 42px;
        line-height: 42px;
        margin-top: 32px;
    }
    .form-region-text {
        color: #666666;
        font-size: 14px;
        line-height: 24px;
    }
    .form-change-region {
        // width:488px;
        // height:36px;
        background:rgba(255,255,255,1);
        border-radius:4px;
        border:1px solid rgba(220,223,230,1);
        padding-left: 16px;
        line-height: 36px;
        color: #999999;
        cursor: pointer;
        display: flex;
        .form-region-city {
            // width: 488px;
            // height: 36px;
            display: block;
            // overflow: hidden;
            line-height: 36px;
            // white-space: nowrap;
            text-overflow: ellipsis;
            p {
                display: inline-block;
            }
        }
    }
    .zd-foot {
        padding-left: 74px;
        height: 36px;
        display: flex;
        align-items: center;
        margin-top: 24px;
    }
}
</style>
<style lang="less">
    .goodfreightEdit{
        .el-table__body-wrapper .el-table__body .el-table__row td {
            border: none;
        }
        .el-table__header-wrapper .el-table__header .has-gutter tr th {
            border: none;
            padding: 0;
            background: #F2F2F2;
            color: #333333;
            font-size: 14px;
            font-weight: 500;
        }
        .el-table .el-table_1_column_6  .cell {
            position: relative;
        }
        .el-range-editor--small .el-range-separator{
            padding: 0 1px !important;
        }
        .form .el-form-item {
            margin-bottom: 14px;
        }
        .el-table th, .el-table tr {
            background: #fdfdfd;
        }
        .el-table {
            border: none;
        }
        .el-table--border::after, .el-table--group::after {
            top: 0;
            right: 0;
            width: 0px;
            height: 100%;
        }
        .el-table::before {
            left: 0;
            bottom: 0;
            width: 100%;
            height: 0px;
        }
        .el-table__body-wrapper {
            height: auto !important;
        }
        .el-table .cell, .el-table--border td:first-child .cell, .el-table--border th:first-child .cell {
            padding-left: 24px;
        }
    }
</style>